/**
 * http://usejsdoc.org/
 */
var http = require('http'),
	fs = require('fs'),
	url = require('url'),
	querystring = require('querystring');

/**
 * @desc 获取http请求时post的数据
 * @param req http请求对象
 * @param res http响应对象
 */
function resAdd(req,res){
	var postData = '';
	//设置接收数据编码格式为UTF-8
	req.setEncoding('utf-8');
	//接收数据块并将其赋值给postData
	req.addListener('data',function(postDataChunk){
		postData += postDataChunk;
	});
	//接收数据完毕执行回调
	req.addListener('end',function(){
		var param = querystring.parse(postData);
		console.log(postData);
		console.log(param);
		res.writeHead( 200 , {"Content-Type":"text/html"});
		res.end('success');
	});
}

/**
 * @desc 默认首页函数
 * @param req http请求对象
 * @param res http响应对象
 */
function resDefault(req,res){
	var realPath = __dirname + '/'+ url.parse('index.html').pathname;
	var indexPage = fs.readFileSync(realPath);
	res.writeHead( 200 , {"Content-Type":"text/html"});
	res.end(indexPage);
}

/**创建http服务器*/
http.createServer(function(req,res){
	/**web客户端请求*/
	var pathname = url.parse(req.url).pathname;//获取url请求路径
	var realPath = __dirname + pathname;
	console.log(realPath);
	switch (pathname) {
		case '/add': resAdd(req,res);
			break;
		default:resDefault(req,res);
			break;
	}
}).listen(8080,'127.0.0.1');
console.log('Server running at http://127.0.0.1:8080');